﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TankIt.Models
{
    public abstract class Deck : IDeck
    {
        public Guid DeckID { get; set; }
        public bool AcesHigh { get; set; }
        public Card.Value StartAt { get; set; }
        public Card.Value StopAt { get; set; }
        public List<Card> Cards { get; set; }

        protected Deck(bool shuffle = true, bool AcesHigh = true, Card.Value StartAt = Card.Value.Two, Card.Value StopAt = Card.Value.King)
        {
            this.DeckID = Guid.NewGuid();
            this.AcesHigh = AcesHigh;
            this.StartAt = StartAt;
            this.StopAt = StopAt;
            this.Cards = new List<Card>();

            FillDeck();

            if (shuffle)
                this.Shuffle();
        }

        private void FillDeck()
        {
            for (var suit = Card.Suit.Hearts; suit <= Card.Suit.Diamonds; suit++)
            {
                for (var val = this.StartAt; val <= this.StopAt; val++)
                {
                    this.Cards.Add(new Card(suit, val));
                }

                this.Cards.Add(new Card(suit, Card.Value.Ace));
            }
        }

        public virtual void Shuffle()
        {
            List<Card> shuffledCards = new List<Card>();
            Random rnd = new Random();
            int rndCard;

            while (this.Cards.Count() > 0)
            {
                rndCard = rnd.Next(0, this.Cards.Count);
                shuffledCards.Add(this.Cards[rndCard]);
                this.Cards.RemoveAt(rndCard);
            }

            this.Cards = shuffledCards;
        }

        public virtual Card GetNextCard()
        {
            var nextCard =  this.Cards[0];
            this.Cards.RemoveAt(0);
            return nextCard;
        }
    }
}